package com.duojuhe.common.utils.encryption.md5;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @date 2018/2/9.
 */
public class MD5Util {
    /**
     * 需要辅助key最终加密成32位md5
     * @param str
     * @param key
     * @return
     */
    public static String getMD532(String str,String key) throws Exception {
        if (StringUtils.isNotBlank(str)&&StringUtils.isNotBlank(key)) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            str = str+key;
            md.update(str.getBytes());
            byte[] b = md.digest();
            StringBuilder su = new StringBuilder();
            int offset = 0;
            for(int bLen = b.length; offset < bLen; ++offset) {
                String haxHex = Integer.toHexString(b[offset] & 255);
                if (haxHex.length() < 2) {
                    su.append("0");
                }
                su.append(haxHex);
            }
            return su.toString();
        } else {
            return "";
        }
    }

    /**
     * 32位加密
     * @param str
     * @return
     */
    public static String getMD532(String str) {
        try {
            if (StringUtils.isNotBlank(str)) {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(str.getBytes());
                byte[] b = md.digest();
                StringBuilder su = new StringBuilder();
                int offset = 0;
                for(int bLen = b.length; offset < bLen; ++offset) {
                    String haxHex = Integer.toHexString(b[offset] & 255);
                    if (haxHex.length() < 2) {
                        su.append("0");
                    }
                    su.append(haxHex);
                }
                return su.toString();
            } else {
                return "";
            }
        } catch (NoSuchAlgorithmException var7) {
            return "";
        }
    }
}
